package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        //1.检查参数(文章id)
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章id不能为空");
        }
        //2.根据userId或设备id获取到行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "查询对应行为实体信息失败");
        }
        //3.根据行为实体和阅读请求保存阅读行为数据
            //先查询是否有对应的阅读行为
        ApReadBehavior readBehavior = this.getOne(Wrappers.<ApReadBehavior>lambdaQuery()
                .eq(ApReadBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApReadBehavior::getArticleId, dto.getArticleId()));
        if (readBehavior == null) {
            //如果没有阅读行为数据则添加
            readBehavior = new ApReadBehavior();
            readBehavior.setEntryId(apBehaviorEntry.getId());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount((short) 1);
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            this.save(readBehavior);
        } else {
            // 如果存在阅读行为数据,则修改阅读次数+修改更新时间
            readBehavior.setCount((short) (readBehavior.getCount() + 1));
            readBehavior.setUpdatedTime(new Date());
            this.updateById(readBehavior);
        }
        //返回
        return ResponseResult.okResult();
    }
}
